package com.itheima.my_reggie.web.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.my_reggie.common.ApplicationContext;
import com.itheima.my_reggie.common.Result;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

//配置登录的过滤器
@WebFilter("/*")
@Slf4j
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
//      设置允许登录的路径
        String [] paths={
                "/employee/login",
                "/employee/logout",
                "/backend",
                "/user/login",
                "/user/sendMsg",
                "/front"
                };
//      获取当前的虚拟访问路径
        String url = request.getRequestURL().toString();
//      遍历允许登录的路径并与当前的路径进行比对，如何符合则放行
        for (String path : paths) {
            if(url.contains(path)){
                filterChain.doFilter(servletRequest,servletResponse);
                return;
            }
        }
//      获取session传递的数据id，如何session的值不为空，则放行
        Object emp = request.getSession().getAttribute("emp");
        if(emp!=null){
            ApplicationContext.setCurrentId((Long) emp);
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }

        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录，用户id为：{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            ApplicationContext.setCurrentId(userId);

            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
//          否则返回json数据至前台，跳转至登录首页
            servletResponse.getWriter().write(JSON.toJSONString(Result.error("NOTLOGIN")));


    }
}
